#include <iostream>

#include "InetAddr.h"
#include <memory>
#include "Socket.hpp"
#include <stdlib.h>
#include "protocol.h"
using namespace std;


void Usege(string argv)
{
    cout << argv << "sever_ip + sever_port" << endl;
}


int main(int args,char* argv[])
{
    EnableCout();
    if(args != 3)
    {
        Usege(argv[0]);
        exit(1);
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    InetAddr addr(ip,port);
    unique_ptr<Socket> client = make_unique<TcpSocket>();
    auto ret = client->BuildClientSocket(addr);
    user_protocol::Factory fac;
    string out;
    while(ret)
    {
        //0.制造请求
        shared_ptr<user_protocol::Request> req = fac.BuildRequest();
        cout << "——————————————————————————————————————————"<<endl;
        cout <<req->_x << " " << req->_y << " " <<req->_oper <<endl;
        //1.序列化
        string send_str;
        req->Serialization(&send_str);

        //2.添加长度报头 (!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!忘记返回了)
        send_str = user_protocol::Encode(send_str);

        //3.发送
        client->Send(send_str);

        //4.接收回复
        int n = client->Recv(&out);
        if(n <= 0) 
        {
            LOG(FATAL,"accept回复 error");
            break;
        }

        //5.回复去掉报头，确保是一个完整的回复
        string package = user_protocol::Decode(out);
        if(package.empty()) continue;

        //6.反序列化成想要的数据
        shared_ptr<user_protocol::Response> res = fac.acceptResponse();
        res->DeSerialization(package);

        //打出来看看回复
        cout <<"[" << out << "]" <<endl;
    }
}